package com.sdy.mvc.config;

import com.sdy.common.utils.StringUtil;
//import com.sdy.mvc.filter.XFrameFilter;
import com.sdy.mvc.filter.FsFilter;
import com.sdy.mvc.interceptor.ContextInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;

@Configuration
@ComponentScan({"com.sdy.mvc.service", "com.sdy.mvc.interceptor", "com.sdy.mvc.exception", "com.sdy.mvc.filter", "com.sdy.mvc.aop"})
@ServletComponentScan({"com.sdy.mvc.filter"})
public class SdyMvcConfig {
    
    @Autowired
    private ContextInterceptor contextInterceptor;
    @Autowired
    private FsFilter fsFilter;
    
    public static final String SERVICE_REQ_TOKEN_ENC = "inner_token_enc";

    /**
     * 一些web配置
     *
     * @return
     */
    @Bean(name = "baseWebMvcConfigurer")
    public WebMvcConfigurer webMvcConfigurer() {
        /**
         * 添加拦截器
         */
        return new WebMvcConfigurer() {
            /**
             * 拦截器配置
             * @param registry
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(contextInterceptor)
                        .addPathPatterns("/**")
                        .excludePathPatterns("/opt/file/**", "/static/**", "/webjars/**")
                        .order(11);
            }
        };
    }
    
    @Bean
    public FilterRegistrationBean filterXFrameRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(fsFilter);
        registration.addUrlPatterns(FsFilter.FILE_UPLOAD_URL_GET);
        registration.setOrder(12);
        return registration;
    }
    
    public static boolean isServiceCall(HttpServletRequest request) {
        String url = request.getRequestURI();
        return StringUtil.isNotBlank(request.getHeader(SERVICE_REQ_TOKEN_ENC))
                && url.startsWith("/".concat(FeignConfig.RPC_URL_PREFIX).concat("/"));
    }
}
